package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.sys.core.constant.state.ManagerStatus;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.SaltUtil;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.KbParam;
import cn.stylefeng.guns.sys.modular.system.ApiEntity.MtYqParam;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMddy;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMtyq;
import cn.stylefeng.guns.sys.modular.system.entity.Role;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMtyqParam;
import cn.stylefeng.guns.sys.modular.system.service.BtyMddyService;
import cn.stylefeng.guns.sys.modular.system.service.BtyMtyqService;
import cn.stylefeng.guns.sys.modular.system.service.RoleService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.KoubeiTradeTicketTicketcodeQueryRequest;
import com.alipay.api.request.KoubeiTradeTicketTicketcodeUseRequest;
import com.alipay.api.request.KoubeiTradeTicketUsedRefundRequest;
import com.alipay.api.response.KoubeiTradeTicketTicketcodeQueryResponse;
import com.alipay.api.response.KoubeiTradeTicketTicketcodeUseResponse;
import com.alipay.api.response.KoubeiTradeTicketUsedRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dianping.orderdish.openplatform.BasicResponseModel;
import com.dianping.orderdish.openplatform.client.ApiClient;
import com.dianping.orderdish.openplatform.client.DefaultApiClient;
import com.dianping.orderdish.openplatform.dto.tuangou.OrderSkuDTO;
import com.dianping.orderdish.openplatform.dto.tuangou.apis.TuangouCouponCancelAPI;
import com.dianping.orderdish.openplatform.dto.tuangou.apis.TuangouCouponMatchConsumeAPI;
import com.dianping.orderdish.openplatform.dto.tuangou.apis.TuangouCouponStatusQueryAPI;
import com.dianping.orderdish.openplatform.dto.tuangou.request.CouponCancelRequest;
import com.dianping.orderdish.openplatform.dto.tuangou.request.CouponStatusQueryRequest;
import com.dianping.orderdish.openplatform.dto.tuangou.request.TuangouMatchConsumeRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 口碑验券接口
 */
@CrossOrigin
@Controller
@RequestMapping("/kb")
public class KbController {

    private static Logger logger = LoggerFactory.getLogger(KbController.class);

    @Resource
    private RoleService roleService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private BtyMtyqService mtyqService;
    @Resource
    private AuthService authService;
    @Resource
    private BtyMddyService mddyService;



    /**
     *美团测试密钥
     */
//    private static final String appKey = "2151709e084c53eef3d123c033d78c9657e96df9";
//    private static final String appSecret = "8c8c6b54504a12c0a9ee55d3b12bc216295c88be";
    /**
     * 美团正式密钥
     */
    private static final String appKey = "9fb6ddbda24570d916356130755176beefa1caaf";
    private static final String appSecret = "b4b5695e9385bd4b076d12cd6a5b56aef21684e5";

    private static  final String appId="2021002179622836";
    private static  final String alipayrsaPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmFzRyEnlmjOjFb59WjciKCTNFedzAuEfeZxKHUV8qTp+LDB9fzIbaCA5O8vCUDmGYwI13wf08GNFlGzZQpmx0AjqdW5fjTBsNRD5d1pJs0HK10jiuoc7G6tUYCd/A6TAjjwIHCvNm3GEa4qV/SCSwFCzlmcZ6QRzXZHyMrzPXvU37m7nm6dlhqPWmjSR1HMWScqj1gOsfe9lcULxJaLCzKwQqDQo5s+HICA+qNuHDwA3xf5UGyHiwkFCYWgM2cocprm7O7A9d6b694NzIVFAaW6x64qnLpwv7Dmqfu+20nvP5JPUF22GPPrWDh1B2F6qPhUELEHBXHwOaVCljWinDwIDAQAB";
    private static  final String  rsaPrivateKey="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCcH9tYxXfF4Jicgf6GzUd9NmO83QCDtho7mo/qSy+aJqCV8hEgTtE8pb/MToGGqI1LxtwMWyjoAkP/IbLVadRvijSf1i/MB2LgnUp8wlkBrd0PvEnmn5RL/uEwoTF8iEfCZmMdTAxPtiuofZQSajjdIC3Wg5i7V9raKmHSkz5YQ5geoEyDicnIiKozP2FxasoCsXn/58AzaFpezxOv+joE2A3mcedekEmQdf9+plY/sXGn0J0jVhDYG/BxjSflwSEugzoB5a63Q3j9skPoDRVYV56Nx3pjtY3GWhd1zIeD4tm4N1QETwXtkmO9HkPJtROwq5Rc+6dAb8CsSYuOFVUdAgMBAAECggEAbYtsvLzRbWZJrocHsE4Y+yJOmRX4ZnI/tdKdaCeZHvA7fPp8Sc8DwSoLia8L8xARFDpT69eKvD/atglPEa9P/3NZuUzv/JiyKCg1O5SiHyt/EKtsrwUJaMlN+HEh5983eo+cu9HAUa3gtDhozQL7IyyQ/RMY91qNlMZoHPhzpjmuvCO3OVCe8vUhkM34Pco/CQdRdlfpb6f7uqJgZfPStY/ITYkgws5RSk+d9tjDQH/ejjZvO/D81cErCi2gSx/SfZHg5ghN3LGMydo/U+Cwod08CQbVg44yLEzqRdYg7npBYM8Biwlotdx7ww+ZiiYRb4dZ3fycQUbDBweXN8g0AQKBgQDNUqqvfZWxz7EFj12Ne1jPaLS03LzS3FSoRhWp8qstUwXhuWiAaIuDogI4/T4EQfrmx7wAL4N4i7kmPo3N2Iqibg5prBbd5S/Z+n7crhV7VXKTEU9E1Psy3tEZRXdMeb0EONWZ+pkdCdh7cTugMNobw9HTIdECrVjBNpHkC2e9FQKBgQDCqJVOHqwqH5Eo+MXO6FbDFwM2zzUVNBARv3tx41Hw2eP/1O8ifEJNAmZeQJzoNUc0ZQp5Cs14BBGMrLbJb19N9Bhc8JFr9eNKPTz436VFjfOqLpo+aDolIlRQNggN8TvWDzwfy0woUIvYzM1HtQFLiPL/6OovXUWmIWTTKRKJ6QKBgBtulAdmS/25tfj8Mo+Yj0EGyD3xz/iMH3NsCbDvDxe7I+oIj4G4dgtcNdfPXd3Lwu3aea+8qWANqusFKIT8DWmuMpbDuzpiSIZjBVgOmigkPm6PvXuAyR7+zgkGUu4QxcQuo7sy1AohKp8zfbflTv6upvYCap5k8pq947gIHhARAoGAUwqEFz1yiM3KqUXnbOslCDjrABjJNnBtYoTjbqRhMnRhlaQLGBUWW6/oZ9D8nvsLk0h/fT+kg8yIiBCuMaS3bZPySMO/5eSRv/v75NfTs6ZpCnKzDmh8VZcdjNJgAUKmGh2Jsq6RoKkr36MO98Y59TVJJO8B6I7LxaF9V6+v3vECgYBfNdL5gqJoD9H+BvLYdoAfZcXVJVHlF+y09W9+4CcYTcpCSncFPmB9uFI0FwqfOt98QwQ8konNHYHFDL1aDd3Swe8BJ2YPAfs760cbLWDH9VPih3TVgYWVySJ9kXv6W4Cf/l1iFvESRStO9QsIniNOpRL/60wdCH9R/Wo8i1ty5Q==";


    @GetMapping("/userAccess")
    @ResponseBody
    public ResponseData userAccess(HttpServletRequest request) {
        String phone = request.getParameter("phone");
        Map<String, Object> map = new HashMap<>();
        List<String> roleList = new ArrayList<>();
        User users = userMapper.getAccount(phone);
        if (ToolUtil.isNotEmpty(users)) {
            String[] roles = users.getRoleId().split(",");
            for (String role : roles) {
                Role role1 = roleService.getById(role);
                if (ToolUtil.isNotEmpty(role1))
                    roleList.add(role1.getName());
            }
            map.put("roleList", roleList);
        } else {
            return ResponseData.error(Integer.valueOf(502), "查不到用户信息");
        }
        return ResponseData.success(map);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData loginVali(@RequestBody UserDto users,HttpServletResponse response){
        String username = users.getUsername();
        String password =  users.getPassword();

        if (ToolUtil.isOneEmpty(username, password)) {
            return ResponseData.error("账号或密码为空");
        }
        User user = userMapper.getByAccount(username);

        // 账号不存在
        if (null == user) {
            return ResponseData.error(1402, "账号密码错误");
        }

        //验证账号密码是否正确
        String requestMd5 = SaltUtil.md5Encrypt(password, user.getSalt());
        String dbMd5 = user.getPassword();
        if (dbMd5 == null || !dbMd5.equalsIgnoreCase(requestMd5)) {
            return ResponseData.error(1402, "账号密码错误");
        }
        // 账号被冻结
        if (!user.getStatus().equals(ManagerStatus.OK.getCode())) {
            return ResponseData.error(1404, "账号被冻结");
        }
        //登录并创建token
        String token = authService.login(username);
        //生成业务系统token
        //redisService.saveRedis(CacheKey.YWXTTOKENMAP,token,username);
        //request.getSession().setAttribute("token",token);
        return new SuccessResponseData(token);
    }


    /**
     * 口碑撤销验券
     */
    @PostMapping("/cxYq")
    @ResponseBody
    public ResponseData cxYq(@RequestBody KbParam kb) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,rsaPrivateKey,"json","GBK",alipayrsaPublicKey,"RSA2");
        KoubeiTradeTicketUsedRefundRequest request=new KoubeiTradeTicketUsedRefundRequest();
        String requestId = DateUtil.getStampNow();
        String ticket_code=kb.getTicketCode();
        String transId=kb.getTransId();
        request.setBizContent("{" +
                "\"request_id\":\""+requestId+"\"," +
                "\"ticket_code\":\""+ticket_code+"\"," +
                "\"trans_id\":\""+transId+"\"" +
                "  }");
        KoubeiTradeTicketUsedRefundResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return ResponseData.success("退款成功！");
        } else {
            return ResponseData.error(Integer.parseInt(response.getCode()),response.getSubMsg());
        }
    }

    /**
     * 口碑验券
     * @param mtYqParam
     * @return
     * @throws Exception
     */
    @PostMapping("/yqKb")
    @ResponseBody
    public ResponseData yq( @RequestBody MtYqParam mtYqParam) throws Exception {
         //外部请求号，支持英文字母和数字，由开发者自行定义(不允许重复)
        String requestId = DateUtil.getStampNow();
        //券码
        String couponCode=mtYqParam.getCouponCode();
        //门店id
        String vendorShopId=mtYqParam.getVendorShopId();
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,rsaPrivateKey,"json","GBK",alipayrsaPublicKey,"RSA2");
        KoubeiTradeTicketTicketcodeUseRequest request=new KoubeiTradeTicketTicketcodeUseRequest();
        request.setBizContent("{" +
                "  \"request_id\":\""+requestId+"\"," +
                "  \"ticket_code\":\""+couponCode+"\"," +
                "  \"shop_id\":\""+vendorShopId+"\"" +
                "}");
        KoubeiTradeTicketTicketcodeUseResponse response=alipayClient.execute(request);
        if (response.isSuccess()) {
            //return ResponseData.success("验券成功！");
            return ResponseData.success(response);
        } else {
            return ResponseData.error(Integer.parseInt(response.getCode()),response.getSubMsg());
        }

    }

    /**
     * 口碑券码查询接口
      * @param btyMtyqParam
     * @return
     * @throws Exception
     */
    @GetMapping("/queryKb")
    @ResponseBody
    public ResponseData queryKb(BtyMtyqParam btyMtyqParam) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,rsaPrivateKey,"json","GBK",alipayrsaPublicKey,"RSA2");
        KoubeiTradeTicketTicketcodeQueryRequest request = new KoubeiTradeTicketTicketcodeQueryRequest();
        String couponCode=btyMtyqParam.getCode();
        String vendorShopId=btyMtyqParam.getVendorShopId();
        request.setBizContent("{" +
                "  \"ticket_code\":\""+couponCode+"\"," +
                "  \"shop_id\":\""+vendorShopId+"\"" +
                "}");
        KoubeiTradeTicketTicketcodeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return  ResponseData.success(response);
        } else {
            return ResponseData.error(Integer.parseInt(response.getCode()),response.getSubMsg());
        }
    }
    /**
     * 美团口碑验券
     * @param mtYqParam
     * @return
     * @throws Exception
     */
//    @PostMapping("/yqs")
//    @ResponseBody
//    public ResponseData mtYqs( @RequestBody MtYqParam mtYqParam) throws Exception {
//        String orderId = DateUtil.getStampNow();
//        String couponCode = mtYqParam.getCouponCode();
//        String vendorShopId = mtYqParam.getVendorShopId();
//        String eId = mtYqParam.getEId();
//        String eName = mtYqParam.getEName();
//         //根据门店id的长度判断是口碑店还是美团店 length>20口碑店
//        //String code=couponCode.substring(0,2);
//        if(vendorShopId.length()>20){
//            //外部请求号，支持英文字母和数字，由开发者自行定义(不允许重复)
//            String requestId = DateUtil.getStampNow();
//            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,rsaPrivateKey,"json","GBK",alipayrsaPublicKey,"RSA2");
//            KoubeiTradeTicketTicketcodeUseRequest request=new KoubeiTradeTicketTicketcodeUseRequest();
//            request.setBizContent("{" +
//                    "  \"request_id\":\""+requestId+"\"," +
//                    "  \"ticket_code\":\""+couponCode+"\"," +
//                    "  \"shop_id\":\""+vendorShopId+"\"" +
//                    "}");
//            KoubeiTradeTicketTicketcodeUseResponse response=alipayClient.execute(request);
//            if (response.isSuccess()) {
//                System.out.println(response);
//                return ResponseData.success("验券成功！");
//
//                //return ResponseData.success(response);
//            } else {
//                return ResponseData.error(Integer.parseInt(response.getCode()),response.getSubMsg());
//            }
//        }else {
//
//            List<OrderSkuDTO> lists = new ArrayList<>();
//            OrderSkuDTO dto = new OrderSkuDTO();
//            List<MtYqParam.OrderSkusBean> listOrderSkusBean = mtYqParam.getOrderSkus();
//            BigDecimal toPayAmounts = BigDecimal.ZERO;
//            BigDecimal unitPrice = BigDecimal.ZERO;
//            String date = DateUtil.getNowDate();
//            String month = date.substring(0, 7);
//            for (MtYqParam.OrderSkusBean skusBean : listOrderSkusBean) {
//                unitPrice = skusBean.getUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP);
//                toPayAmounts = toPayAmounts.add(unitPrice);
//                dto.setVendorSkuId(skusBean.getVendorSkuId());
//                dto.setVendorSkuName(skusBean.getVendorSkuName());
//                dto.setUnit("个");
//                dto.setUnitPrice(unitPrice);
//                dto.setCount(1);
//                lists.add(dto);
//            }
//            TuangouMatchConsumeRequest request = new TuangouMatchConsumeRequest();
//            request.setOrderSkus(lists);
//            request.setVendorOrderId(orderId);
//            request.setToPayAmount(toPayAmounts);
//            request.setCouponCode(couponCode);
//            request.setVendorShopId(vendorShopId);
//            request.setEId(eId);
//            request.setEName(eName);
//            TuangouCouponMatchConsumeAPI api = new TuangouCouponMatchConsumeAPI();
//            api.setRequest(request);
//            ApiClient client = new DefaultApiClient(appKey, appSecret);
//            BasicResponseModel rsp = client.execute(api);
//            String result = JSON.toJSONString(rsp);
//            System.out.println("result:" + JSON.toJSONString(rsp));
//            System.out.println("code:" + rsp.getCode() + rsp.getMsg());
//            if (rsp.getCode() == 200) {
//                return ResponseData.success("验券成功！");
//            } else {
//                return ResponseData.error(rsp.getCode(), rsp.getMsg());
//            }
//        }
//
//    }

    /**
     * 美团口碑券码查询
     * @param btyMtyqParam
     * @return
     * @throws Exception
     */
//    @GetMapping("/query")
//    @ResponseBody
//    public ResponseData query(BtyMtyqParam btyMtyqParam) throws Exception {
//        //门店id
//        String vendorShopId=btyMtyqParam.getVendorShopId();
//        //券码
//        String couponCode=btyMtyqParam.getCode();
//        //根据门店id的长度判断是口碑店还是美团店 length>20口碑店
//        //口碑店
//        if(vendorShopId.length()>20){
//            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,rsaPrivateKey,"json","GBK",alipayrsaPublicKey,"RSA2");
//            KoubeiTradeTicketTicketcodeQueryRequest request = new KoubeiTradeTicketTicketcodeQueryRequest();
//            //String couponCode=btyMtyqParam.getCode();
//            //String vendorShopId=btyMtyqParam.getVendorShopId();
//            request.setBizContent("{" +
//                    "  \"ticket_code\":\""+couponCode+"\"," +
//                    "  \"shop_id\":\""+vendorShopId+"\"" +
//                    "}");
//            KoubeiTradeTicketTicketcodeQueryResponse response = alipayClient.execute(request);
//            if(response.isSuccess()){
//                return  ResponseData.success(response);
//            } else {
//                return ResponseData.error(Integer.parseInt(response.getCode()),response.getSubMsg());
//            }
//        }
//        //美团券码
//        else{
//            CouponStatusQueryRequest request=new CouponStatusQueryRequest();
//            request.setCouponCode(couponCode);
//            request.setVendorShopId(vendorShopId);
//            TuangouCouponStatusQueryAPI api=new TuangouCouponStatusQueryAPI();
//            api.setRequest(request);
//            ApiClient client = new DefaultApiClient(appKey, appSecret);
//            BasicResponseModel rsp = client.execute(api);
//            System.out.println("rsp:"+rsp);
//            if(rsp.getCode() == 200){
//                return ResponseData.success(rsp.getContent());
//            }else{
//                return ResponseData.error(rsp.getCode(),rsp.getMsg());
//            }
//        }
//
//    }
    @GetMapping("/queryMts")
    @ResponseBody
    public ResponseData queryMts(BtyMtyqParam btyMtyqParam) throws Exception {
        //门店id
        String vendorShopId=btyMtyqParam.getVendorShopId();
        //券码
        String couponCode=btyMtyqParam.getCode();
        CouponStatusQueryRequest request=new CouponStatusQueryRequest();
        request.setCouponCode(couponCode);
        request.setVendorShopId(vendorShopId);
        TuangouCouponStatusQueryAPI api=new TuangouCouponStatusQueryAPI();
        api.setRequest(request);
        ApiClient client = new DefaultApiClient(appKey, appSecret);
        BasicResponseModel rsp = client.execute(api);
        if(rsp.getCode() == 200){
            return ResponseData.success(rsp.getContent());
        }else{
            return ResponseData.error(rsp.getCode(),rsp.getMsg());
        }

    }

    /**
     * 美团撤销验券
     * @param mtYqParam
     * @return
     * @throws Exception
     */
    @PostMapping("/cxYqs")
    @ResponseBody
    public ResponseData cxYq(@RequestBody MtYqParam mtYqParam) throws Exception {

        JSONObject json = new JSONObject();
        String couponCode = mtYqParam.getCouponCode();
        String vendorShopId = mtYqParam.getVendorShopId();
        String eId = mtYqParam.getEId();
        String eName = mtYqParam.getEName();

        json.put("couponCode", couponCode);
        json.put("vendorShopId", vendorShopId);
        json.put("eId", eId);
        json.put("eName", eName);

        CouponCancelRequest cancelRequest=new CouponCancelRequest();
        cancelRequest.setCouponCode(couponCode);
        cancelRequest.setVendorShopId(vendorShopId);
        cancelRequest.setEId(eId);
        cancelRequest.setEName(eName);

        TuangouCouponCancelAPI api=new TuangouCouponCancelAPI();
        api.setRequest(cancelRequest);
        ApiClient client = new DefaultApiClient(appKey, appSecret);
        BasicResponseModel rsp = client.execute(api);

        if (rsp.getCode()==200) {
            //更新当前券的状态为已撤销
            BtyMtyq mtyq = mtyqService.getOne(new QueryWrapper<BtyMtyq>().eq("code", couponCode));
            if (ToolUtil.isNotEmpty(mtyq)) {
                mtyq.setState(25);
                mtyq.setUpdateTime(new Date());
                mtyqService.updateById(mtyq);
            }
            return ResponseData.success("撤销验券成功！");
        } else {
            return ResponseData.error(rsp.getCode()+rsp.getMsg());
        }

    }

    @GetMapping("/dmList")
    @ResponseBody
    public ResponseData dmList(){
        List<BtyMddy> list=mddyService.list();
       return ResponseData.success(list);
    }

    /**
     * 美团口碑券码查询
     * @param btyMtyqParam
     * @return
     * @throws Exception
     */
    @GetMapping("/query")
    @ResponseBody
    public ResponseData querys(BtyMtyqParam btyMtyqParam) throws Exception {
        //妖码
        String yaoma=btyMtyqParam.getYaoma();
        //根据妖码获取门店id
        BtyMddy mddy=mddyService.getOne(new QueryWrapper<BtyMddy>().eq("yaoma",yaoma));
        String mtShopId="";
        String kbShopId="";
        String jhId="";
        String vendorShopId="";
        List<String>list=new ArrayList<>();

        //券码
        String couponCode=btyMtyqParam.getCode();
        if(ToolUtil.isNotEmpty(mddy)){
            mtShopId=mddy.getMtShopId()==null?"":mddy.getMtShopId();
            kbShopId=mddy.getKbShopId()==null?"":mddy.getKbShopId();
            list.add(mtShopId);
            list.add(kbShopId);
           // jhId=mddy.getJhMerchantId()==null?"":mddy.getJhMerchantId();
        }

        for (String s : list) {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,rsaPrivateKey,"json","GBK",alipayrsaPublicKey,"RSA2");
            KoubeiTradeTicketTicketcodeQueryRequest request1 = new KoubeiTradeTicketTicketcodeQueryRequest();
            request1.setBizContent("{" +
                    "  \"ticket_code\":\""+couponCode+"\"," +
                    "  \"shop_id\":\""+s+"\"" +
                    "}");
            KoubeiTradeTicketTicketcodeQueryResponse response = alipayClient.execute(request1);
            if(response.isSuccess()){
                return  ResponseData.success(response);
            } else {
                if(Integer.parseInt(response.getCode())==40004){
                    CouponStatusQueryRequest request=new CouponStatusQueryRequest();
                    request.setCouponCode(couponCode);
                    request.setVendorShopId(s);
                    TuangouCouponStatusQueryAPI api=new TuangouCouponStatusQueryAPI();
                    api.setRequest(request);
                    ApiClient client = new DefaultApiClient(appKey, appSecret);
                    BasicResponseModel rsp = client.execute(api);
                    System.out.println("rsp:"+rsp);
                    if(rsp.getCode() == 200){
                        return ResponseData.success(rsp.getContent());
                    }else{
                        return ResponseData.error(rsp.getCode(),rsp.getMsg());
                    }
                }else {
                    return ResponseData.error(Integer.parseInt(response.getCode()), response.getSubMsg());
                }
            }
        }
        return null;
    }

    /**
     * 用户绑定
     * @param request
     * @return
     */
    @PostMapping("/userBind")
    @ResponseBody
    public ResponseData userBind(HttpServletRequest request) {

        String account=request.getParameter("account");
        String yaoma=request.getParameter("yaoma");
        User users = userMapper.selectOne(new QueryWrapper<User>().eq("account",account));
        if (ToolUtil.isNotEmpty(users)) {
         //根据妖码绑定用户到美团口碑对应表
            BtyMddy mddy=mddyService.getOne(new QueryWrapper<BtyMddy>().eq("yaoma",yaoma));
            if(ToolUtil.isNotEmpty(mddy)){
                mddy.setAccount(account);
                mddyService.updateById(mddy);
                return ResponseData.success("绑定成功!");
            }else{
                return ResponseData.error(501,"绑定失败");
            }
        } else {
            return ResponseData.error(502, "查不到用户信息");
        }
    }

    /**
     * 美团口碑验券
     * @param mtYqParam
     * @return
     * @throws Exception
     */
    @PostMapping("/yqs")
    @ResponseBody
    public ResponseData mtYq( @RequestBody MtYqParam mtYqParam) throws Exception {
        //妖码
        String yaoma=mtYqParam.getYaoma();
        //根据妖码获取门店id
        BtyMddy mddy=mddyService.getOne(new QueryWrapper<BtyMddy>().eq("yaoma",yaoma));
        String mtShopId="";
        String kbShopId="";
        String jhId="";
        String vendorShopId="";
        List<String>list=new LinkedList<>();



        //券码
        String couponCode=mtYqParam.getCouponCode();
        if(ToolUtil.isNotEmpty(mddy)){
            mtShopId=mddy.getMtShopId()==null?"":mddy.getMtShopId();
            kbShopId=mddy.getKbShopId()==null?"":mddy.getKbShopId();
            list.add(kbShopId);
            list.add(mtShopId);
            // jhId=mddy.getJhMerchantId()==null?"":mddy.getJhMerchantId();
        }

        String orderId = DateUtil.getStampNow();
//        String couponCode = mtYqParam.getCouponCode();
//        String vendorShopId = mtYqParam.getVendorShopId();
        String eId = mtYqParam.getEId();
        String eName = mtYqParam.getEName();
        //根据门店id的长度判断是口碑店还是美团店 length>20口碑店
        //String code=couponCode.substring(0,2);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).length()>20){
                //外部请求号，支持英文字母和数字，由开发者自行定义(不允许重复)
                String requestId = DateUtil.getStampNow();
                AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,rsaPrivateKey,"json","GBK",alipayrsaPublicKey,"RSA2");
                KoubeiTradeTicketTicketcodeUseRequest request1=new KoubeiTradeTicketTicketcodeUseRequest();
                request1.setBizContent("{" +
                        "  \"request_id\":\""+requestId+"\"," +
                        "  \"ticket_code\":\""+couponCode+"\"," +
                        "  \"shop_id\":\""+list.get(i)+"\"" +
                        "}");
                KoubeiTradeTicketTicketcodeUseResponse response=alipayClient.execute(request1);
                if(response.isSuccess()){
                    return  ResponseData.success(response);
                } else {
                    return ResponseData.error(Integer.parseInt(response.getCode()), response.getSubMsg());
                }
            }else{
                String shopId=list.get(1);
                List<OrderSkuDTO> lists = new ArrayList<>();
                OrderSkuDTO dto = new OrderSkuDTO();
                BigDecimal toPayAmounts = BigDecimal.ZERO;
                BigDecimal unitPrice = BigDecimal.ZERO;
                if(ToolUtil.isNotEmpty(mtYqParam.getOrderSkus())){
                    List<MtYqParam.OrderSkusBean> listOrderSkusBean = mtYqParam.getOrderSkus();
                    String date = DateUtil.getNowDate();
                    for (MtYqParam.OrderSkusBean skusBean : listOrderSkusBean) {
                        unitPrice = skusBean.getUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP);
                        toPayAmounts = toPayAmounts.add(unitPrice);
                        dto.setVendorSkuId(skusBean.getVendorSkuId());
                        dto.setVendorSkuName(skusBean.getVendorSkuName());
                        dto.setUnit("个");
                        dto.setUnitPrice(unitPrice);
                        dto.setCount(1);
                        lists.add(dto);
                    }
                }
                TuangouMatchConsumeRequest request = new TuangouMatchConsumeRequest();
                request.setOrderSkus(lists);
                request.setVendorOrderId(orderId);
                request.setToPayAmount(toPayAmounts);
                request.setCouponCode(couponCode);
                request.setVendorShopId(shopId);
                request.setEId(eId);
                request.setEName(eName);
                TuangouCouponMatchConsumeAPI api = new TuangouCouponMatchConsumeAPI();
                api.setRequest(request);
                ApiClient client = new DefaultApiClient(appKey, appSecret);
                BasicResponseModel rsp = client.execute(api);
                String result = JSON.toJSONString(rsp);
                System.out.println("result:" + JSON.toJSONString(rsp));
                System.out.println("code:" + rsp.getCode() + rsp.getMsg());
                if (rsp.getCode() == 200) {
                    return ResponseData.success("验券成功！");
                } else {
                    return ResponseData.error(rsp.getCode(), rsp.getMsg());
                }
            }

        }
        return null;
    }


}
